package com.yvdedu.my161121.addressbook.biz.service.impl;

import com.yvdedu.my161121.addressbook.biz.entity.Useable;
import com.yvdedu.my161121.addressbook.biz.service.LoginService;
import com.yvdedu.my161121.addressbook.biz.mapper.UseableMapper;
import com.yvdedu.my161121.addressbook.biz.mapper.LoginMapper;
import com.yvdedu.my161121.addressbook.biz.entity.User;
import org.springframework.stereotype.Service;
import com.yvdedu.my161121.addressbook.biz.entity.Login;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UseableMapper useableMapper;

    @Resource
    private LoginMapper loginMapper;

    @Override
    public User login(String loginName, String password) throws LoginException, PasswordException {
        Login dbLogin = loginMapper.get(loginName);

        if (dbLogin == null) {
            throw new LoginException();
        }
        if (!dbLogin.getPassword().equals(password)) {
            throw new PasswordException();

        }
        return dbLogin.getUser();
    }

    @Override
    public UrlAccessTester getAccessUrls(int roleId) {
        return new DefaultUrlAccessTester(useableMapper.getAccessUrls(roleId));

    }

    @Override
    public List<Useable> getMenuData(int roleId) {
        return useableMapper.getMenuData(roleId, UseableMapper.ROOT_ID);
    }


    private class DefaultUrlAccessTester implements UrlAccessTester {

        private static final long serialVersionUID = 1L;
        private Set<String> urls = new HashSet<String>();
        private String[] regexArray;

        public DefaultUrlAccessTester(List<String> accessUrls) {
            List<String> regexList = new ArrayList<String>();
            for (String url : accessUrls) {
                if (url.startsWith("^") || url.endsWith("$")) {
                    regexList.add(url);
                } else {
                    urls.add(url);
                }
            }
            regexArray = regexList.toArray(new String[0]);
        }

        @Override
        public boolean isAccess(String url) {
            if (urls.contains(url)) {
                return true;
            }
            for (String reg : regexArray) {

                if (url.matches(reg)) {
                    return true;

                }
            }
            return false;
        }


    }


}
 
